package com.sys.location.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.core.aspect.Log;
import com.sys.location.entity.Everyday;
import com.sys.location.entity.Location;
import com.sys.location.service.EverydayService;
import com.sys.location.service.LocationService;
import com.utils.MapDistanceUtil;
import com.utils.TmStringUtils;
import com.utils.ip.TmIpUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/location")
public class LocationController {

	@Autowired
	LocationService locationService;
	
	@Autowired
	EverydayService everydayService;

	@Value("${locationAddr}")
	private String locationAddr;

	  @Log("定位")
	  @PostMapping(value="/getLocation.do")
	  @ResponseBody
	  public void getLocation(HttpServletRequest request,String lon,String lat){
		  if(TmStringUtils.isNotEmpty(lon) && TmStringUtils.isNotEmpty(lat)) {
			  String host=request.getRemoteHost();//来访者的主机名
			  String ipLocation=TmIpUtil.ipLocation(host, locationAddr);//qqwry.dat文件获取ip所在的城市
			  QueryWrapper<Location> wrapper=new QueryWrapper<Location>();
			  wrapper.eq("ip", host);
			  List<Location> list=locationService.selectList(wrapper);
			  Location view=MapDistanceUtil.getLocation(lon,lat);
			  if(view!=null) {
				  view.setIp(host);
				  view.setIpAddr(ipLocation);
				  if(list!=null && !list.isEmpty()) {
					  UpdateWrapper<Location> userUpdateWrapper = new UpdateWrapper<Location>();
					  userUpdateWrapper.eq("ip", host);
					  locationService.update(view, userUpdateWrapper);
				  }else {
					  locationService.insert(view);
				  } 
			  }
		  }else {
			  log.info("定位失败");
		  }
	  }

	  
	  @Log("每日一句")
	  @PostMapping(value="/api.do")
      public String api(HttpServletRequest request,HttpServletResponse response){
		  Everyday view=everydayService.queryToday();
		  if(view!=null) {
			return view.getContent();
		  }
		  return "error";
	  }
	  
	
}
